<template>
  <div class="bg-red-50 flex flex-col min-h-screen">
    <div class="flex flex-col">
      <nut-input
        v-if="usertype === 'customer'"
        class="mb-2"
        v-model="select"
        placeholder="请输入想要查找到的服务人员"
        type="text"
        max-length="50"
      >
        <template #right>
          <nut-button type="primary" size="small" @click="selectuser(select)">搜索</nut-button>
        </template>
      </nut-input>
      <div class="h-[120px] mb-2">
        <nut-swiper
          :init-page="1"
          :auto-play="3000"
          pagination-visible
          pagination-color="#426543"
          pagination-unselected-color="#808080"
          class="h-[120px]"
        >
          <nut-swiper-item v-for="(item, index) in Carouselimagelist" :key="index">
            <img :src="item" alt="Swiper Image" class="h-full w-full" draggable="false" />
          </nut-swiper-item>
        </nut-swiper>
      </div>
    </div>
    <div class="sticky top-0 z-10 bg-red-50">
      <div class="bg-white rounded-lg mx-2.5 p-2.5">
        <nut-grid :column-num="5" :border="false">
          <nut-grid-item v-for="(item, index) in displayedServices" :key="index" @click="handleClickService(item)">
            <div class="flex flex-col items-center justify-center w-full">
              <div class="w-10 h-10 mb-1 flex items-center justify-center">
                <img :src="item.icon || defaultIcon" alt="service icon" class="w-full h-full object-contain rounded" />
              </div>
              <div class="text-xs text-gray-800 text-center truncate w-full leading-tight" :title="item.name">
                {{ item.name.length > 15 ? item.name.slice(0, 11) + "..." : item.name }}
              </div>
            </div>
          </nut-grid-item>
        </nut-grid>
      </div>
      <div v-if="selectedService" class="bg-white rounded-lg mx-2.5 mt-2 p-3">
        <div class="space-y-2">
          <div class="flex items-start">
            <span class="text-gray-600 w-20">服务描述：</span>
            <span class="text-gray-800 flex-1">{{ selectedService.description }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-600 w-20">价格：</span>
            <span class="text-gray-800">¥{{ selectedService.price }}</span>
          </div>
          <div class="flex items-center">
            <span class="text-gray-600 w-20">预计时长：</span>
            <span class="text-gray-800">{{ selectedService.duration }}分钟</span>
          </div>
          <div class="flex justify-end mt-2">
            <nut-button type="default" size="small" @click="cancelService">取消</nut-button>
          </div>
        </div>
      </div>
    </div>

    <div class="px-2.5 pt-3 flex-grow overflow-y-auto">
      <list v-if="usertype === 'customer'" :list="greatuserList" :type="type" />
      <list v-else-if="usertype === 'service'" :serverlist="serverList" :type="type" @updateList="initializeData" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { selectapi } from "@/api/home";
import jiadianweixiu from "@/static/swiper/jiadianweixiu.png";
import xinjiafuw1 from "@/static/swiper/xinjiafuwu1.png";
import xinjiafuw2 from "@/static/swiper/xinjiafuwu2.png";
import list from "@/components/list.vue";
import { uerPersonStore } from "@/store/modules/person";

// 默认图标
const defaultIcon = ref(
  ""
);

//初始化仓库
const usertype = ref();
const usepersonStore = uerPersonStore();

//搜索内容
const select = ref<any>();
const type = ref<string>();

//优秀员工数据
const greatuserList = ref([]);
//需求数据
const serverList = ref([]);

// 添加选中的服务状态
const selectedService = ref<any>(null);

//轮播图
const Carouselimagelist = ref([jiadianweixiu, xinjiafuw1, xinjiafuw2]);

//服务类型数据
const servertype = ref<any>([]);
// 控制服务类型是否全部显示
const showAllServices = ref(false);

// 服务类型接口
interface ServiceType {
  name: string;
  description?: string;
  price?: number;
  duration?: number;
  icon?: string;
}

// 计算属性，用于显示的服务类型
const displayedServices = computed(() => {
  const collapseItem = { name: "收起", icon: defaultIcon.value };
  const allItem = { name: "打开", icon: defaultIcon.value };

  if (servertype.value.length <= 8) {
    return servertype.value;
  } else {
    if (showAllServices.value) {
      return [...servertype.value, collapseItem];
    } else {
      return [...servertype.value.slice(0, 7), allItem];
    }
  }
});

// 修改初始化方法
const initializeData = async () => {
  try {
    // 每次初始化时重新获取最新的用户类型
    usertype.value = uni.getStorageSync("usertype") || "";

    // 重置所有数据
    greatuserList.value = [];
    serverList.value = [];
    type.value = "";
    selectedService.value = null;

    // 获取服务类型
    await usepersonStore.getServerType();
    servertype.value = usepersonStore.servertype;

    // 根据用户类型获取相应数据
    if (usertype.value === "customer") {
      await usepersonStore.getserverperson();
      greatuserList.value = usepersonStore.serverperson;
    } else if (usertype.value === "service") {
      await usepersonStore.getDemand();
      serverList.value = usepersonStore.demand;
    }
  } catch (error) {
    console.error("初始化数据失败：", error);
  }
};

// 添加 onMounted 钩子
onMounted(async () => {
  usertype.value = uni.getStorageSync("usertype") || "";
  await initializeData();
});

const selectuser = async (item: any) => {
  if (!item) return; // 如果搜索内容为空，不发送请求
  const res: any = await selectapi(item);
  if (res && res.data) {
    greatuserList.value = res.data.records;
  }
};

const goServer = (serviceType: string) => {
  type.value = serviceType;
  console.log(type.value);
};

// 修改点击处理逻辑
const handleClickService = (item: any) => {
  if (item.name === "打开") {
    showAllServices.value = true;
  } else if (item.name === "收起") {
    showAllServices.value = false;
  } else {
    const selectedServiceData = servertype.value.find((service: ServiceType) => service.name === item.name);
    if (selectedServiceData) {
      selectedService.value = {
        description: selectedServiceData.description || "暂无描述",
        price: selectedServiceData.price || 0,
        duration: selectedServiceData.duration || 0,
      };
    }
    goServer(item.name);
  }
};

// 添加取消服务的方法
const cancelService = () => {
  selectedService.value = null;
  type.value = "";
};
</script>

<style scoped></style>
